import api from "@/common/api";
import React, { useEffect, useRef, useState } from "react";
import styled from "styled-components";
import gsap from "gsap"; //滚动的包
const itemHeight = 50; //每行的高度
const duration = 200; //
const RollCardItemStyle = styled.div<{ height: number }>`
  padding-top: ${(props) => props.height / 2 + "px"};
  color: #fff;
  overflow: hidden;
`;
const RollCardItemWrap = styled.div<{ height: number; totalHeight: number }>`
  height: ${(props) => props.totalHeight + "px"};

  position: relative;
`;
const RollCardItem = styled.div<{ height: number; index: number }>`
  height: ${(props) => props.height + "px"};
  line-height: ${(props) => props.height + "px"};
  font-size: 20px;
  transform: translate3d(0, 0, 0);
  position: absolute;
  left: 0;
  top: ${(props) => props.index * itemHeight + "px"};
  width: 100%;
  border: 1px solid pink;
`;
function T1Block() {
    // 滚动的列表，全量数据
  const [productList, setProduct] = useState<productModel.Datum[]>([]);
    // 错误重试次数
  const retryCountRef = useRef(3);
    // 接口请求信息
  const pageInfoRef = useRef({
    pageSize: 10,
    current: 1,
    total: 0,
  });
    // 滚动的位置，记录一下
  const currentTranslateRef = useRef(0);
    // 用来做虚拟列表，记录滚动到哪里了，触发界面渲染
  const [currentTranslateState, setCurrentTranslateState] = useState(0);

    // 滚动
  const startGsap = () => {
    currentTranslateRef.current+=1
    gsap.to(
      ".RollCardItem",
      {
        duration: duration / 1000,
        opacity: (_, target) => {
            const index = Number(target.tabIndex);
            if (currentTranslateRef.current -1 === index) {
              return 0;
            } else {
              return 1;
            }
        },
        top: (_, target) => {
            const index = Number(target.tabIndex);
            const rpx =
              -currentTranslateRef.current * itemHeight +
              index * itemHeight +
              "px";
            console.log(index, rpx, "index");
            return rpx;
        },
        // 
        onComplete: () => {

            if (
                currentTranslateRef.current ===
                pageInfoRef.current.total - pageInfoRef.current.pageSize - 1
              ) {
                setProduct((pro) =>
                  pro.concat(
                    pro.map((p) => ({
                      ...p,
                      id: p.id + Math.random(),
                    }))
                  )
                );
              }
            // 单次滚动结束，开始我们的判断
            if (currentTranslateRef.current >= pageInfoRef.current.total ) {
                //到头了,重新请求第一页
                pageInfoRef.current.current = 1;
                currentTranslateRef.current = 0;

                init(1);
              } else if (
                currentTranslateRef.current >
                  pageInfoRef.current.pageSize * (pageInfoRef.current.current-1)
                     &&
                pageInfoRef.current.current * pageInfoRef.current.pageSize + 1 <
                  pageInfoRef.current.total
              ) {
                // 滚一半,中途静默请求
                // debugger
    
                init(pageInfoRef.current.current + 1);
    
                
              }else{
                requestAnimationFrame(() => {
                    setTimeout(() => {
                      startGsap();
                    }, duration);
                  });
              }
        }
      },
    );
  };
    // 接口请求函数
  const getProductList = (current?: number) => {
    const c = current || pageInfoRef.current.current;
    // 一次性请求两页,可能到头了
    // if (
    //   c !== 1 &&
    //   c  * pageInfoRef.current.pageSize -pageInfoRef.current.total > pageInfoRef.current.pageSize
    // ) {
    //   // debugger
    //   return Promise.reject({});
    // }
    return new Promise((resolve, reject) => {
      api
        .invoke<productModel.RootObject>("get", "https://www.fastmock.site/mock/e72b19c73672e123df1ac95ef5c0eebc/project/v1/products/list", {
          pageSize: pageInfoRef.current.pageSize,

          current: c,
        })
        .then(
          (res) => {
            pageInfoRef.current.current = res.current;
            pageInfoRef.current.total = res.total;
            retryCountRef.current = 3;
            if (res.current === 1) {
              setProduct(res.data);
            } else {
              setProduct((pro) => pro.concat(res.data));
            }

            resolve({});
          },
          () => {
            if (retryCountRef.current) {
              // 接口报错了,从头开始
              retryCountRef.current--;
              currentTranslateRef.current = 0;
              pageInfoRef.current = {
                pageSize: 10,
                current: 1,
                total: 0,
              };
              setTimeout(() => {
                init(1);
              }, 1000);
            }
          }
        );
    });
  };
  const init = (start: number) =>{
    getProductList(start).then(() => {
        getProductList(start + 1);
        // if (pageInfoRef.current.current === 1) {
          setTimeout(() => {
            startGsap();
          }, duration);
        // }
    });
  }
  useEffect(()=>{
    init(1)
  },[])

  return (
    <RollCardItemStyle height={itemHeight}>
      <RollCardItemWrap
        className="RollCardItemWrap"
        totalHeight={itemHeight * (pageInfoRef.current.pageSize - 2)}
        height={itemHeight}
      >
       {
        (productList||[]).map((p,index)=>{
            return  <RollCardItem
            className={"RollCardItem RollCardItem" + index}
            key={p.id + p.name}
            index={index}
            height={itemHeight}
            tabIndex={index}
          >
            {p.name}
          </RollCardItem>
        })
       }
      </RollCardItemWrap>
    </RollCardItemStyle>
  );
}

export default T1Block;
